
package com.mephi.controller.action;


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import com.mephi.MephistoChess;
import com.mephi.interfaces.Game;
import com.mephi.interfaces.ImportExportGame;
import com.mephi.interfaces.LoginManager;
import com.mephi.interfaces.Profile;
import com.mephi.io.ImportExportGameImpl;
import com.mephi.model.Move;
import com.mephi.model.profile.LoginManagerImpl;
import com.mephi.util.Ext;
import com.mephi.util.filter.FileFilter;


/**
 * Simple implementation of export game action in another thread.
 * @author mephisto
 * 2011-05-28
 * 1.0
 */
public class ExportGameAction implements Runnable
{	
	@Override
	public void run()
	{
		logger.info("Export has been started");
		LoginManager loginManager = LoginManagerImpl.INSTANCE;
		if (loginManager.isSomebodyLoggedIn())
		{
			ImportExportGame<Move> exporter = new ImportExportGameImpl();

			JFileChooser chooser = new JFileChooser();
	        chooser.setCurrentDirectory(new File("."));
	        List<String> extensionList =  new ArrayList<String>();
	        extensionList.add(Ext.txt.toString());
	        chooser.setFileFilter(new FileFilter(extensionList));
	        int r = chooser.showSaveDialog(MephistoChess.gui.getFraMainFrame());
	        if (r != JFileChooser.APPROVE_OPTION) return;
	        //final File file = chooser.getSelectedFile();
	        logger.info("Selected file: " + chooser.getSelectedFile().getAbsolutePath());
	        
			Profile profile = loginManager.getCurrentProfile();		
			//FAKE
			Game<Move> game = profile.getGameMap().get("1");
			//String path = "exportFile.txt";
			//END FAKE
			String path = chooser.getSelectedFile().getAbsolutePath();
			
			try
			{
				exporter.exportGame(game, path, Ext.txt);
			}
			catch (FileNotFoundException e)
			{
				logger.error(e);
				logger.error("Export has been finished with errors!");
				JOptionPane.showMessageDialog(MephistoChess.gui.getFraMainFrame(),
						e, title, JOptionPane.ERROR_MESSAGE);
			}
			logger.info("Export has been finished");
		}
		else
		{
			String errMsg = "Nobody is currently logged in! Please log in first!";
			logger.warn(errMsg);
			JOptionPane.showMessageDialog(MephistoChess.gui.getFraMainFrame(),
					errMsg, title, JOptionPane.ERROR_MESSAGE);
		}
	}	

	
	private static String title = "Export error";
	private Logger logger = Logger.getLogger("LOG");
}
